<?php

namespace app\admin\controller\business;

//引入进来基类控制器
use app\common\controller\Backend;

/**
 * 客户公海控制器
 */
class Highsea extends Backend
{
    // 关联查询
    protected $relationSearch = true;
    //当前模型
    protected $model = null;

    //当前无须登录方法
    protected $noNeedLogin = [];

    //无需鉴权的方法,但需要登录
    protected $noNeedRight = [];

    //构造函数
    public function __construct()
    {
        parent::__construct();

        // 将控制器和模型关联
        $this->model = model('Business.Business');
        // 客户领取模型
        $this->ReceiveModel = model('Business.Receive');
        // 管理员模型
        $this->AdminModel = model('Admin');
    }

    // 客户公海列表
    public function index()
    {
        //将请求当中所有的参数去除html标签，去掉两边空白
        $this->request->filter(['strip_tags', 'trim']);
        // 判断是否有ajax请求
        if ($this->request->isAjax()) {
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            //获取表格所提交过来筛选和排序的一些参数
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            //表格需要两个返回值参数 总条数，分页的数据
            $total = $this->model
                ->with('source')
                ->where('adminid', 'NULL')
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->count(); //返回查询的总数

            //返回多条数据，是二维数组结构
            $list = $this->model
                ->with('source')
                ->where('adminid', 'NULL')
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            //组装数据
            $result = ['total' => $total, 'rows' => $list];

            //返回json数据给ajax结果
            return json($result);
        }
        return $this->view->fetch();
    }

    // 领取客户资源
    public function apply($ids = null)
    {
        $ids = !empty($ids) ?  explode(',', $ids) : [];
        $row = $this->model->all($ids);

        if (!$row) {
            $this->error(__('No Results were found'));
            exit;
        }

        $list = [];
        $businessList = [];
        foreach ($row as $value) {

            $list[] = [
                'applyid' => $this->auth->id,
                'status' => 'apply',
                'busid' => $value['id']
            ];

            $businessList[] = [
                'id' => $value['id'],
                'adminid' => $this->auth->id
            ];
        }

        // 开启事务
        $this->model->startTrans();
        $this->ReceiveModel->startTrans();

        // 更新客户表
        $BusinessStatus = $this->model->saveAll($businessList);

        if ($BusinessStatus === FALSE) {
            $this->error($this->model->getError());
        }
        // 插入领取表
        $ReceiveStatus = $this->ReceiveModel->saveAll($list);

        if ($ReceiveStatus === FALSE) {
            $this->model->rollback();
            $this->error($this->ReceiveModel->getError());
        }

        if ($ReceiveStatus === FALSE || $BusinessStatus === FALSE) {
            $this->model->rollback();
            $this->ReceiveModel->rollback();
            $this->error('申请失败');
        } else {
            $this->model->commit();
            $this->ReceiveModel->commit();
            $this->success('申请成功');
        }
        return $this->view->fetch();
    }

    /** 
     * 分配客户资源
     * 管理员表 拿到所有的管理员（当前管理员和下级管理员信息）
     * 客户表   拿到当前选中客户信息（显示客户名称列表）
     * 修改客户表中的adminid字段
     * 客户领取表 添加领取信息
     */
    public function recovery($ids = NULL)
    {
        // 获取客户id列表（多选或单选）
        $ids = !empty($ids) ? explode(',', $ids) : [];
        $row = $this->model->all($ids);

        if (!$row) {
            $this->error(__('No Results were found'));
            exit;
        }
        // var_dump($ids);
        // exit;

        // 判断界面列表请求是否有发送过来
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            // var_dump($params);
            // exit;

            // 申请人信息
            $list = [];
            // 客户信息
            $businessList = [];

            // 使用foreach循环组装数据
            foreach ($row as $value) {
                $list[] = [
                    'applyid' => $params['adminid'],
                    'status' => 'allot',
                    'busid' => $value['id']
                ];

                $businessList[] = [
                    'id' => $value['id'],
                    'adminid' => $params['adminid']
                ];
            }

            // 开启事务
            $this->model->startTrans();
            $this->ReceiveModel->startTrans();

            // 更新客户表
            $BusinessStatus = $this->model->saveAll($businessList);

            if ($BusinessStatus === FALSE) {
                $this->error($this->model->getError());
            }

            // 插入领取表
            $ReceiveStatus = $this->ReceiveModel->saveAll($list);

            if ($ReceiveStatus === FALSE) {
                $this->model->rollback();
                $this->error($this->ReceiveModel->getError());
            }

            if ($ReceiveStatus === FALSE || $BusinessStatus === FALSE) {
                $this->model->rollback();
                $this->ReceiveModel->rollback();
                $this->error('分配失败');
            } else {
                $this->model->commit();
                $this->ReceiveModel->commit();
                $this->success('分配成功');
            }
        }
        $AdminData = $this->AdminModel->column('id,username');

        $this->assign([
            'AdminData' => $AdminData,
            'row' => $row
        ]);

        return $this->view->fetch();
    }

    //删除 （软删除，修改deltetime字段）
    public function del($ids = NULL)
    {
        $ids = !empty($ids) ?  explode(',', $ids) : [];

        $row = $this->model->column('id');

        foreach ($ids as $item) {
            if (!in_array($item, $row)) {
                $this->error(__('没有找到该用户'));
                exit;
            }
        }

        $result = $this->model->destroy($ids);

        if ($result === false) {
            $this->error($this->model->getError());
            exit;
        }

        $this->success();
        exit;
    }
}
